import { Injectable, Post } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getConnection } from 'typeorm';
import { PostEntity } from './posts.entity';
import { CommonObjectProps } from '../typings';

@Injectable()
export class PostsService {
  constructor(
    @InjectRepository(PostEntity)
    private readonly postsRepository: Repository<PostEntity>,
  ) {}

  async addPost(post: CommonObjectProps): Promise<PostEntity> {
    return await this.postsRepository.save(post);
  }

  async posts(): Promise<PostEntity[]> {
    return await this.postsRepository.find();
  }

  // 查单个
  async getPost(id: number): Promise<PostEntity> {
    return await this.postsRepository.findOne({ where: { id } });
  }

  // 更新
  async update(id: number, post: CommonObjectProps) {
    const result = await getConnection()
      .createQueryBuilder()
      .update(PostEntity)
      .set(post)
      .where('id=:id', { id })
      .execute();
    return result;
  }

  // 删除
  async delete(id: number) {
    const result = await getConnection()
      .createQueryBuilder()
      .delete()
      .from(PostEntity)
      .where('id=:id', { id })
      .execute();
    return result;
  }
}
